package com.st.controller.background;

import com.ramostear.captcha.HappyCaptcha;
import com.st.entity.Admin;
import com.st.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private IAdminService adminService;

    @GetMapping("login")
    public String login() {
        return "/background/login";
    }

    @PostMapping("login")
    public ModelAndView login1(Admin user,String captcha,HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        boolean flag = HappyCaptcha.verification(request,captcha,true);
        if (!flag){
            mv.addObject("errorMsg", "验证码错误！");
            mv.setViewName("/background/login");
            return mv;
        }
        //md5加密和加盐处理
        String md5Pass2= String.valueOf(DigestUtils.appendMd5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8), new StringBuilder("wzf")));
        String md5Pass = DigestUtils.md5DigestAsHex(md5Pass2.getBytes(StandardCharsets.UTF_8));
        user.setPassword(md5Pass);
        List<Admin> list = adminService.query(user);
        if (list.size() == 0) {
            mv.addObject("errorMsg", "用户名不存在！");
            mv.setViewName("/background/login");
            return mv;
        } else {
            if (user.getUsername().equals(list.get(0).getUsername()) && user.getPassword().equals(list.get(0).getPassword())) {
                HttpSession session= request.getSession();
                session.setAttribute("userName",user.getUsername());
                //设置过期事件啊
                session.setMaxInactiveInterval(60*10);
                mv.addObject("manager", list.get(0).getUsername());
                mv.addObject("permissionManagement", list.get(0).getGrade());
                mv.setViewName("/background/index");

                return mv;
            } else {
                mv.addObject("errorMsg", "用户名或密码错误！");
                mv.setViewName("/background/login");
                return mv;
            }
        }
    }
    @GetMapping("/captcha")
    public void happyCaptcha(HttpServletRequest request, HttpServletResponse response){
        HappyCaptcha.require(request,response).build().finish();
    }


}
